$(document).ready(function(){
	var $as = $("#slideShow li a");
	var prefix = "/dorimeme/app/webroot/img/pic/ex/action-photos-";
	$as.each(function(index, elem){
		var imgUrl = prefix;
		index ++;
		imgUrl += index;
		imgUrl +=".jpg";
		$(elem).css("background", "url('"+imgUrl+"') no-repeat scroll 0 0 transparent");
		$(elem).children().text(liName[index%7]);
	});
	slideshow = new SlideShow("#slideShow");
	setInterval('slideshow.refresh()',12000);
});


/**
 * Representing the slide show div
 * @param {Object} slideShowSel slide show selector
 */
function SlideShow(slideShowSel){
	this.$container = $(slideShowSel);
	this.$rows = this.$container.children(".showRow");
	
	this.$container.css("position", "relative");
	this.$rows.css("position", "absolute");
	
	this.$rows.each(function(index, row){
		$(row).css("top", 150*(index)+"px");
	});

}
index = 0;
size = 32;

odd = true;
var liName = ["music", "art", "creative", "speed", "action", "technology", "behavior"];
function createLi(){
	
	// create new li and its children
	var $newLi = $("<li></li>");
	var $newA = $("<a href='#'></a>");
	
	index = (index + 1) % size;
	temp = index + 1;
	var imgUrl = "/dorimeme/app/webroot/img/pic/ex/action-photos-"+temp+".jpg";
	$newA.css("background", "url('"+imgUrl+"') no-repeat scroll 0 0 transparent");

	var $newSpan = $("<span></span>");
	$newSpan.text(liName[index%7]);
	
	// organize them into a tree
	$newA.append($newSpan);
	$newLi.append($newA);
	return $newLi;
	
}

SlideShow.prototype = {
	/**
	 * insert new li before the first element
	 * @param {Object} $newLi
	 * @param {Object} rowNum
	 */
	insertLi : function($newLi, rowNum){
		// insert newLi ul
		$rowN = $(this.$rows.get(rowNum));
		$rowN.width("1050px");
		$rowN.css("left","-150px");
		$newLi.insertBefore($rowN.children().first());
		if (this.$rows.get(rowNum + 1)) {
			this.insertLi($rowN.children().last().clone(), rowNum + 1);
		}
	},
	
	/**
	 * move every row to right in order
	 * @param {Object} rowNum
	 */
	animateUls : function(rowNum){
		// make sure all paras can work
		if(!rowNum){
			rowNum = 0;
		}
		_this = this;
		var $thisRow = $(this.$rows.get(rowNum));
		
		// animate thisRow ,when animation ends,call the next row to animate
		$thisRow.animate({left : "0px"}, "slow",function(){
			if (_this.$rows.get(rowNum + 1)) {
				_this.animateUls(rowNum + 1);
			}else{
				// when there is no more rows, remove last li in every line
				_this.removeLi();
			}
		});
	},
	
	/**
	 * remove last li in all rows
	 */
	removeLi : function(){
		this.$rows.each(function(){
			$(this).children().last().remove();
		});
	},
	
	/**
	 * this function is called when we get a new li to insert
	 * it will refresh slide show smoothly
	 */
	refresh : function(){
		this.insertLi(createLi(), 0);
		this.animateUls(0)
	}
}